package com.sztz.utils;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * DataLoad方式批量操作数据到DB
 * @author yzy
 * @date 2022/08/03 14:21
 */
@Slf4j
public class DbLoadDataUtils {
    /**
     * 组装LOAD DATA LOCAL INFILE的sql语名
     * @param dbName 数据库名
     * @param tableName 表名
     * @param columns 列名字符串，用逗号分隔
     * @return String 拼装好的sql
     * @author yzy
     * @date 2022/7/27 14:59
     */
    public static String createSql(String dbName,String tableName,String columns){
        String sqlTemplate="LOAD DATA LOCAL INFILE '' REPLACE INTO TABLE {}.{} CHARACTER SET utf8 FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' escaped by '\"' LINES TERMINATED BY '\\n'  ({})  ";
        return StrUtil.format(sqlTemplate,dbName,tableName,columns);
    }
    /**
     * 组装LOAD DATA LOCAL INFILE的sql语名
     * @param dataSource 数据源
     * @param loadDataSql 拼装好的SQL
     * @param inputStream 数据流
     * @return int 处理的数据行数
     * @author yzy
     * @date 2022/7/27 14:59
     */
    public static int dbLoadDataFromInputStream(DataSource dataSource, String loadDataSql, InputStream inputStream){
        if(ObjectUtil.isNull(inputStream)){
            throw new IllegalArgumentException("需要导入的数据流不能为空");
        }
        try(
                Connection connection = dataSource.getConnection();
                PreparedStatement ps = connection.prepareStatement(loadDataSql);
        ){
            if(ps.isWrapperFor(com.mysql.jdbc.Statement.class)){
                com.mysql.jdbc.PreparedStatement mysqlStatement = ps.unwrap(com.mysql.jdbc.PreparedStatement.class);
                mysqlStatement.setLocalInfileInputStream(inputStream);
                int result = mysqlStatement.executeUpdate();
                mysqlStatement.close();
                return result;
            }
        }catch (Exception e){
            log.error("dbLoadDataFromInputStream Exception：{}", ExceptionUtil.stacktraceToString(e));
        }
        return 0;
    }
}
